<template>
  <div class="flex flex-col items-center w-50%">
    <h2 class="font-size-36px fw-500 lh-24px mb-48px">注册</h2>
    <div
      ref="scrollContainer"
      class="p-20px w-full box-border bg-#fff max-h-50vh overflow-auto"
    >
      <el-form
        v-show="step === 0"
        ref="registerForm"
        class="login-form"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="认证类型" prop="companyType">
          <el-select
            v-model="formData.companyType"
            placeholder="请选择认证类型"
          >
            <el-option label="不认证" :value="0"></el-option>
            <el-option label="供应商" :value="1"></el-option>
            <el-option label="企业用户" :value="2"></el-option>
            <el-option label="开发者" :value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="formData.email" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="username">
          <el-input
            v-model="formData.username"
            placeholder="请输入"
            :maxlength="11"
          >
          </el-input>
        </el-form-item>
        <el-form-item
          :label="[1, 2].includes(formData.companyType) ? '联系人' : '姓名'"
          prop="nickName"
        >
          <el-input v-model="formData.nickName" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <PwdInput v-model="formData.password" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <PwdInput v-model="formData.confirmPassword" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <el-form
        v-show="step === 1"
        ref="authForm"
        class="login-form"
        :model="authData"
        :rules="authRules"
        label-position="top"
      >
        <template v-if="formData.companyType !== 3">
          <el-form-item label="公司名" prop="companyName">
            <el-input
              v-model="authData.companyName"
              placeholder="请输入"
              :maxlength="20"
            ></el-input>
          </el-form-item>
          <el-form-item label="公司地址" prop="companyAddress">
            <el-input
              v-model="authData.companyAddress"
              placeholder="请输入"
              :maxlength="50"
            ></el-input>
          </el-form-item>
        </template>
        <el-form-item label="联系人" prop="companyContact">
          <el-input
            v-model="authData.companyContact"
            placeholder="请输入联系人"
            :maxlength="10"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="companyContactMobile">
          <el-input
            v-model="authData.companyContactMobile"
            placeholder="请输入联系电话"
            :maxlength="11"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="companyEmail">
          <el-input
            v-model="authData.companyEmail"
            placeholder="请输入企业邮箱"
          ></el-input>
        </el-form-item>
        <template v-if="formData.companyType !== 3">
          <el-form-item label="营业执照" prop="companyLicense">
            <div
              @click="doUpload('companyLicense')"
              class="cursor-pointer w-160px h-160px overflow-hidden"
            >
              <img
                v-if="authData.companyLicense"
                :src="authData.companyLicense"
                class="w-full h-full b-rd-4px"
                alt=""
              />
              <div
                v-else
                class="w-160px h-160px box-border flex items-center justify-center b-rd-4px b-1px b-#dcdfe6 b-dashed"
              >
                <el-icon><Plus /></el-icon>
              </div>
            </div>
          </el-form-item>
        </template>
        <el-form-item label="身份证正反面" v-else>
          <el-form-item prop="idCardUrlFront">
            <div
              @click="doUpload('idCardUrlFront')"
              class="cursor-pointer w-200px h-140px overflow-hidden"
            >
              <img
                v-if="authData.idCardUrlFront"
                :src="authData.idCardUrlFront"
                class="w-full h-full b-rd-4px"
                alt=""
              />
              <div
                v-else
                class="w-full h-full box-border flex items-center justify-center b-rd-4px b-1px b-#dcdfe6 b-dashed"
              >
                <el-icon><Plus /></el-icon>
              </div>
            </div>
          </el-form-item>
          <el-form-item prop="idCardUrlBack" class="ml-20px">
            <div
              @click="doUpload('idCardUrlBack')"
              class="cursor-pointer w-200px h-140px overflow-hidden"
            >
              <img
                v-if="authData.idCardUrlBack"
                :src="authData.idCardUrlBack"
                class="w-full h-full b-rd-4px"
                alt=""
              />
              <div
                v-else
                class="w-full h-full box-border flex items-center justify-center b-rd-4px b-1px b-#dcdfe6 b-dashed"
              >
                <el-icon><Plus /></el-icon>
              </div>
            </div>
          </el-form-item>
        </el-form-item>
      </el-form>
    </div>
    <div
      class="w-full mt-28px mb-30px flex justify-between items-center font-size-16px"
    >
      <el-checkbox v-model="serverChecked" class="h-24px">
        <el-button type="text" @click="goServer('server')"
          >《服务条款》</el-button
        >
        <span>和</span>
        <el-button type="text" @click="goServer('privacy')"
          >《隐私政策》</el-button
        >
      </el-checkbox>
      <span class="link cursor-pointer" @click="changeType('login')"
        >返回登录</span
      >
    </div>
    <el-button
      :loading="loading"
      :disabled="confirmDisabled"
      type="primary"
      class="w-full h-60px font-size-20px"
      @click="doConfirm"
      >{{ confirmText }}</el-button
    >
  </div>
</template>

<script setup>
import { Plus } from "@element-plus/icons-vue";
import { PwdInput } from "@/components";
import { useLoading } from "@/hooks";
import { phoneValidator } from "@/utils/valid";
import { getFile } from "@/utils/dom";
import { shardUpload } from "@/utils/shardUpload";

const scrollContainer = ref();
const { loading, setLoading } = useLoading();
const step = ref(0);
const confirmText = computed(() => {
  if (formData.value.companyType == 0 || step.value === 1) return "注册";
  return "下一步";
});

const registerForm = ref();
const formData = ref({
  email: "",
  username: "",
  nickName: "",
  password: "",
  confirmPassword: "",
  companyType: 0,
});

const confirmValid = (_, val, cb) => {
  if (!val) return cb(new Error("请再次确认密码"));
  if (val !== formData.value.password)
    return cb(new Error("两次输入密码不一致"));
  cb();
};
const rules = reactive({
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    { type: "email", message: "请输入正确的邮箱", trigger: "blur" },
  ],
  username: [{ required: true, validator: phoneValidator, trigger: "blur" }],
  nickName: [{ required: true, message: "请输入", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  confirmPassword: [
    { required: true, validator: confirmValid, trigger: "blur" },
  ],
  companyType: [{ required: true, type: "number", message: "请选择认证类型" }],
});

const authForm = ref();
const authData = ref({
  companyName: "",
  companyAddress: "",
  companyContact: "",
  companyContactMobile: "",
  companyEmail: "",
  companyLicense: "",
  idCardUrlFront: "",
  idCardUrlBack: "",
});
const authRules = reactive({
  companyName: [{ required: true, message: " 请输入公司名" }],
  companyAddress: [{ required: true, message: " 请输入公司地址" }],
  companyContact: [{ required: true, message: " 请输入联系人" }],
  companyContactMobile: [{ required: true, validator: phoneValidator }],
  companyLicense: [{ required: true, message: "请上传营业执照" }],
  idCardUrlFront: [{ required: true, message: "请上传身份证正面" }],
  idCardUrlBack: [{ required: true, message: "请上传身份证反面" }],
});

const doUpload = async (field) => {
  const file = await getFile();
  const data = await shardUpload(file);
  if (!data) return ElMessage.error("上传失败");
  authData.value[field] = data.url;
  authForm.value.validateField(field);
};

const doConfirm = () => {
  if (step.value === 0) {
    registerForm.value.validate((valid) => {
      if (valid) {
        if (formData.value.companyType !== 0) {
          const { companyType, username, nickName, email } = formData.value;
          authData.value.companyContact = nickName;
          authData.value.companyContactMobile = username;
          authData.value.companyEmail = email;
          ++step.value;
          scrollContainer.value.scrollTo({
            top: 0,
          });
        } else {
          doRegister();
        }
      }
    });
  }
  if (step.value === 1) {
    authForm.value.validate((valid) => {
      if (valid) doRegister();
    });
  }
};

const serverChecked = ref(false);
const confirmDisabled = computed(() => {
  if (formData.value.companyType === 0) {
    return !serverChecked.value;
  } else if (step.value === 1) {
    return !serverChecked.value;
  }
  return false;
});

const router = useRouter();
const goServer = (type) => {
  const routeUrl = router.resolve(`/server?type=${type}`).href;
  window.open(routeUrl, "_blank");
};

const $api = inject("$api");
// 处理提交数据
const formatSubmitData = () => {
  const submitData = {
    ...formData.value,
  };
  if (formData.value.companyType !== 0) {
    submitData.companyForm = {
      ...authData.value,
    };
    submitData.companyForm.companyType = submitData.companyType;
    delete submitData.companyType;
  }
  if (
    submitData?.companyForm?.idCardUrlFront &&
    submitData?.companyForm?.idCardUrlBack
  ) {
    submitData.companyForm.idCardUrl = `${submitData.idCardUrlFront},${submitData.idCardUrlBack}`;
    delete submitData.companyForm.idCardUrlFront;
    delete submitData.companyForm.idCardUrlBack;
  }
  return submitData;
};
const doRegister = async () => {
  setLoading(true);
  const submitData = formatSubmitData();
  try {
    const { code } = await $api.system.register(submitData);
    if (code === 200) {
      ElMessage.success("注册成功");
      setTimeout(() => {
        changeType("login");
      }, 1000);
    }
  } finally {
    setLoading(false);
  }
};

const changeType = inject("changeType");
</script>
